#!/usr/bin/env python
# coding:utf-8

import time
import json
import psutil
import random
from paho.mqtt import client as mqtt_client

broker = '192.168.17.237'  # mqtt代理服务器地址
port = 30840
keepalive = 60  # 与代理通信之间允许的最长时间段（以秒为单位）
topic = "LMS/sitsv/toServer/transfer/LHZQ6419/231"  # 消息主题
client_id = '1234'  # 客户端id不能重复


def connect_mqtt():
    '''连接mqtt代理服务器'''

    def on_connect(client, userdata, flags, rc):
        '''连接回调函数'''
        # 响应状态码为0表示连接成功
        if rc == 0:
            print("Connected to MQTT OK!")
        else:
            print("Failed to connect, return code %d\n", rc)

    # 连接mqtt代理服务器，并获取连接引用
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(broker, port, keepalive)
    client.username_pw_set(username="admin", password="public")
    client.subscribe("LMS/sitsv/toTerminal/transfer/+/+", 2)
    client.loop_start()
    return client


def on_message(client, user_data, msg):
    '''订阅消息后，回调该方法'''
    print(str(msg.payload.decode('gb2312')))


def publish(client):
    '''发布消息'''
    # while True:
    #     '''每隔4秒发布一次服务器信息'''
    #     time.sleep(4)
    msg = {
        "ack": "1",
        "url": "transferDetailCommit",
        "data": {
            "electricLabel": "E20047158DA068216270010A",
            "driverIcCard": "E2000017660D024517606352",
            "picUrl": "E2000017660D024517606352",
            "unloadPlace": "二线破碎机口"
        }
    }
    msg = str(msg)

    result = client.publish(topic, msg)
    print(result)
    print('1111111')
    status = result[0]
    if status == 0:
        print(f"Send `{msg}` to topic `{topic}`")
    else:
        print(f"Failed to send message to topic {topic}")


def on_subscribe(client):
    mqttClient = client.subscribe("LMS/prod/toTerminal/oneBody/1/test001", 2)


def run():
    '''运行发布者'''
    client = connect_mqtt()
    publish(client)
    # # 运行一个线程来自动调用loop()处理网络事件, 非阻塞
    # client.loop_start()


if __name__ == '__main__':
    run()
